package com.nut.lmsc.redis;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class RedisClient {

    //    @Autowired
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public Long incrByTTL(final String key, final long number, final int ttl) {
        return redisTemplate.execute((RedisCallback<Long>) connection -> {
            Long value = connection.incrBy(key.getBytes(), number);
            connection.expire(key.getBytes(), ttl);
            return value;
        });
    }

    public Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void set(String key, Object value, long timeout, TimeUnit unit) {
        redisTemplate.opsForValue().set(key, value, timeout, unit);
    }

    public void leftPush(String key, Object value) {
        redisTemplate.opsForList().leftPush(key, value);
    }

    public List<Object> range(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    public Object leftPop(String key, long timeout, TimeUnit unit) {
        return redisTemplate.opsForList().leftPop(key, timeout, unit);
    }

    public void put(String key, Object hashKey, Object value) {
        redisTemplate.opsForHash().put(key, hashKey.toString(), value);
    }

    public Map<Object, Object> entries(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    public void deleteHash(String key, Object... hashKeys) {
        redisTemplate.opsForHash().delete(key, hashKeys);
    }

    public void increment(String key, String hashKeys, long delta) {
        redisTemplate.opsForHash().increment(key, hashKeys, delta);
    }

    public void delete(String key) {
        if (StrUtil.isNotBlank(key)) {
            redisTemplate.delete(key);
        }
    }

    public Boolean setIfAbsent(String key, Object value, long timeout, TimeUnit unit) {
        return redisTemplate.opsForValue().setIfAbsent(key, value, timeout, unit);
    }

    public void setAdd(String key, Object... value) {
        redisTemplate.opsForSet().add(key, value);
    }

    public Object setPop(String key) {
        return redisTemplate.opsForSet().pop(key);
    }
}
